<template>
  <div class="table-group">
    <table-group
      v-model="searchParams.image_group_id"
      :loading="groupLoading"
      :list="[{ name: '全部', _id: 0 }, ...(groupData?.data || [])]"
      :options="{ label: 'name', id: '_id' }"
      @on-create="onGroupCreate"
      @on-edite="onGroupEdite"
      @on-delete="onGroupDelete"
    >
      <template #header>
        <c-select
          width="100%"
          v-model="searchParams.image_type"
          prefixText="类型："
          :loading="typeLoading"
          :optionList="typeGroupData"
          @change="onGroupTypeChange"
        ></c-select>
      </template>
    </table-group>

    <div class="table-group__content">
      <c-table
        row-key="_id"
        class="table-template__table"
        :loading="loading"
        :data="tableData"
        v-model:search="searchParams"
        v-model:paging="paging"
        @refresh="queryTableData"
      >
        <!-- 搜索栏 -->
        <template #search>
          <c-input width="200px" v-model="searchParams._id" placeholder="请输入ID" />
          <c-select
            width="200px"
            v-model="searchParams.use_status"
            prefixText="使用状态："
            :optionList="[{ label: '全部', value: -1 }, ...ImageUseStatus]"
          ></c-select>
          <c-select
            v-if="userType"
            width="200px"
            v-model="searchParams.top_status"
            prefixText="是否顶置："
            :optionList="[
              { label: '未顶置', value: 0 },
              { label: '已顶置', value: 1 },
            ]"
          ></c-select>
        </template>

        <!-- 操作栏 -->
        <template #handle="{ selectionList, selectionLength }">
          <el-button type="primary" @click="hanleModal">批量上传</el-button>
          <el-button
            type="primary"
            :disabled="!selectionLength"
            @click="handleImageBatchUpdate(selectionList)"
          >
            批量修改
          </el-button>
          <!-- <el-button type="primary" :disabled="!selectionLength">批量删除</el-button> -->
        </template>

        <!-- 表格 -->
        <template #table>
          <el-table-column type="selection" width="40"></el-table-column>

          <el-table-column prop="images" label="图片" width="190">
            <template #default="{ row }">
              <el-space :size="4" wrap>
                <el-image
                  v-for="(item, index) in row.images"
                  :key="item"
                  class="image-item"
                  :src="item.url"
                  :preview-src-list="row.images.map((v) => v.url)"
                  :initial-index="index"
                  fit="contain"
                  preview-teleported
                />
              </el-space>
            </template>
          </el-table-column>

          <el-table-column label="ID" min-width="200" v-if="userType == 1">
            <template #default="{ row }">
              <div>ID：{{ row._id }}</div>
              <div>userid：{{ row.userid }}</div>
            </template>
          </el-table-column>

          <el-table-column label="图片信息" min-width="200">
            <template #default="{ row }">
              <div>口令：{{ row.password }}</div>
              <div>分组名称：{{ getGroupEnum?.[row.image_group_id] }}</div>
              <div>图片类型：{{ getTypeGroupEnum?.[row.image_type] }}</div>
            </template>
          </el-table-column>

          <el-table-column label="操作信息" min-width="160">
            <template #default="{ row }">
              <div>预览次数：{{ row.preview_num }}</div>
              <div>下载次数：{{ row.down_num }}</div>
              <div>权重：{{ row.image_sort }}</div>
            </template>
          </el-table-column>

          <el-table-column label="状态信息" min-width="200">
            <template #default="{ row }">
              <div>使用状态：{{ ImageUseStatus.getLabel(row.use_status || 0) }}</div>
              <div v-if="userType">
                是否顶置：<c-switch
                  v-model="row.top_status"
                  :activeValue="1"
                  :inactiveValue="0"
                  :before-change="() => switchBeforeChange(row)"
                  @refresh="queryTableData"
                ></c-switch>
              </div>
              <div>创建时间：{{ row.create_time }}</div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="140" fixed="right" align="center">
            <template #default="{ row }">
              <el-button text type="primary" @click="handleDown(row)">下载</el-button>
              <el-button type="primary" text @click="handleUseStatus(row)">标记使用</el-button>
              <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </c-table>
    </div>
  </div>

  <!-- 弹窗 -->
  <c-dialog title="分组管理" :width="600" name="group-create">
    <group-create :userType="userType" @refresh="queryListGroup"></group-create>
  </c-dialog>

  <c-dialog title="图像管理" :width="600" name="image-batch-update">
    <image-batch-update :userType="userType" @refresh="queryTableData"></image-batch-update>
  </c-dialog>
</template>

<script setup name="el-encap.table-template">
import { ref, computed, onMounted } from 'vue';

// hooks
import { useTable } from '@/hooks/useTable/index.js';
import { useFetch } from '@/hooks/useFetch/index.js';

// components
import Sortable from 'sortablejs';
import GroupCreate from './group-create.vue';
import ImageBatchUpdate from './image-batch-update.vue';
import TableGroup from '@/components/group-menus/table-group.vue';
import { MessageBox } from '@/utils/message-box';
import { ElMessage } from 'element-plus';

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

// api
import { allTypeGroup, userListGroup } from '@/apis/user';
import {
  listGroup,
  pageListImages,
  listUserGroup,
  pageUserListImages,
  editeStatus,
  deleteGroup,
} from '@/apis/images';

import { ImageUseStatus, ImageShowStatus } from '@/config/global-variable';

import { downLoadImg } from '@/utils/tools.js';

import dayjs from 'dayjs';

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const getTypeGroupEnum = computed(() => {
  return typeGroupData.value.reduce(function (obj, item) {
    obj[item.value] = item.label;
    return obj;
  }, {});
});

const getGroupEnum = computed(() => {
  return groupData.value.data.reduce(function (obj, item) {
    obj[item._id] = item.name;
    return obj;
  }, {});
});

// 分组列表
const groupParams = ref({ group_type: '' });
const {
  loading: groupLoading,
  data: groupData,
  queryData: queryListGroup,
} = useFetch({
  api: props.userType == 1 ? listGroup : listUserGroup,
  params: groupParams.value,
  callBack: (res) => {
    return {
      data: res.data.data.map((v) => {
        return { ...v, url: v.group_cover?.url };
      }),
    };
  },
});

// 分类列表
const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: props.userType == 1 ? allTypeGroup : userListGroup,
});

// 表格相关
const searchParams = ref({
  _id: '',
  use_status: -1,
  top_status: 0,
  image_type: '',
  image_group_id: '',
});
const { loading, paging, tableData, queryTableData, delTableRow } = useTable({
  api: props.userType == 1 ? pageListImages : pageUserListImages,
  params: searchParams.value,
  options: {},
  callBack: () => {},
});

// setTimeout(() => {
//   console.log(tableData.value.map((v) => v.images[0].url));
// }, 2000);

// 状态开关
const switchBeforeChange = async (row) => {
  return await editeStatus({ _id: row._id, top_status: row.top_status == 1 ? 0 : 1 }).catch(
    (err) => err,
  );
};

// 添加
const hanleModal = () => {
  if (props.userType == 1) {
    router.push({
      path: '/manage-center/images-list/batch-upload',
      query: {
        group_id: searchParams.value.image_group_id,
        image_type: searchParams.value.image_type,
      },
    });
  } else {
    router.push({
      path: '/user-manage/user-images-list/user-batch-upload',
      query: {
        group_id: searchParams.value.image_group_id,
        image_type: searchParams.value.image_type,
      },
    });
  }
};

// 编辑
const hanleModalEdit = () => {
  modalStore.openModal('popup', { type: 'add', data: [] });
};

// 删除
const handleDelete = (row) => {
  delTableRow({
    api: editeStatus,
    params: { _id: row._id, delete_status: 1 },
  });
};

const handleUseStatus = (item) => {
  MessageBox({
    title: '确定使用该数据？',
    message: '操作不可逆，请谨慎操作',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;

        let res = await editeStatus({
          _id: item._id,
          use_status: 1,
        }).catch((err) => err);

        instance.confirmButtonLoading = false;

        if (res?.code !== 0) return;

        ElMessage.success('操作成功');
        queryTableData();
      }
      done();
    },
  });
};

// 行拖拽
const rowDrop = () => {
  const tbody = document.querySelector('.table-template__table tbody');
  Sortable.create(tbody, {
    group: {
      name: 'shared',
      pull: true,
      put: true,
    },
    handle: '.table-drag-img',
    animation: 150,
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');

      const currRow = tableData.value.splice(oldIndex, 1)[0];

      tableData.value.splice(newIndex, 0, currRow);
    },
  });
};

// 列拖拽
const columnDrop = () => {
  const tr = document.querySelector('.table-template__table tr');
  Sortable.create(tr, {
    animation: 150,
    onEnd: ({ newIndex, oldIndex }) => {
      console.log(newIndex, oldIndex, 'newIndex, oldIndex');
    },
  });
};

const onGroupTypeChange = () => {
  groupParams.value.group_type = searchParams.value.image_type;
  searchParams.value.image_group_id = '';
  queryListGroup();
};

const onGroupCreate = () => {
  modalStore.openModal('group-create');
};

const onGroupEdite = (item) => {
  modalStore.openModal('group-create', item);
};

const handleImageBatchUpdate = (selectionList) => {
  modalStore.openModal('image-batch-update', { selectionList });
};

const onGroupDelete = (item) => {
  MessageBox({
    title: '确定删除该数据？',
    message: '操作不可逆，请谨慎操作',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;

        let res = await deleteGroup({
          _id: item._id,
          delete_status: 1,
        }).catch((err) => err);

        instance.confirmButtonLoading = false;

        if (res?.code !== 0) return;

        ElMessage.success('删除成功');
        queryListGroup();
      }
      done();
    },
  });
};

const handleDown = async (row) => {
  for (const item of row.images) {
    await downLoadImg(
      item.url,
      `${row.password}_${dayjs(Date.now()).format('YYYYMMDDHHmmssSSS')}.png`,
    );
  }
};

onMounted(() => {
  // rowDrop();
  // columnDrop();
});
</script>

<style lang="scss" scoped>
.table-template {
  display: flex;
  flex-direction: column;
}

.image-item {
  width: 50px;
  height: 50px;
  aspect-ratio: 1/1;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
}

.table-group {
  height: 100%;
  display: flex;

  &__content {
    width: 100%;
    overflow: hidden;
    margin-left: 6px;
    padding: 20px;
    box-sizing: border-box;
    @include card-box;
  }
}

.table-drag-img {
  font-size: 20px;
  vertical-align: middle;
  cursor: grab;
  margin: 0;
  padding: 0;
}
</style>
